package pe.edu.sistemas.samupg.application.converter;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

import org.primefaces.component.picklist.PickList;
import org.primefaces.model.DualListModel;

import pe.edu.sistemas.samupg.domain.model.Maestria;

@FacesConverter(value = "maestriaConverter")
public class MaestriaConverter implements Converter {

	public String getAsString(FacesContext context, UIComponent component,
			Object value) {
		return String.valueOf(((Maestria) value).getMaestriaId());
	}

	@SuppressWarnings("rawtypes")
	public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2) { //String arg2 = value
		// Maestria category = new Maestria();
		// category.setMaestriaId(Long.parseLong(value));
		// return category;

		Object ret = null;
		if (arg1 instanceof PickList) {
			Object dualList = ((PickList) arg1).getValue();
			DualListModel dl = (DualListModel) dualList;
			for (Object o : dl.getSource()) {
				String id = "" + ((Maestria) o).getMaestriaId();
				if (arg2.equals(id)) {
					ret = o;
					break;
				}
			}
			if (ret == null)
				for (Object o : dl.getTarget()) {
					String id = "" + ((Maestria) o).getMaestriaId();
					if (arg2.equals(id)) {
						ret = o;
						break;
					}
				}
		}
		return ret;
	}
}
